package com.zhang.teachingcommunity_spring.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.teachingcommunity_spring.mapper.CourseMapper;
import com.zhang.teachingcommunity_spring.mapper.UserCourseMapper;
import com.zhang.teachingcommunity_spring.mapper.entity.Course;
import com.zhang.teachingcommunity_spring.mapper.entity.UserCourse;
import com.zhang.teachingcommunity_spring.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userCourse")
public class UserCourseController {
    @Autowired
    private UserCourseMapper userCourseMapper;
    @Autowired
    private CourseMapper courseMapper;
    @PostMapping("/add")
    private Result insert(@RequestBody UserCourse userCourse) {
        QueryWrapper<UserCourse> userCourseQueryWrapper = new QueryWrapper<>();
        userCourseQueryWrapper.eq("user_id", userCourse.getUserId()).eq("course_id", userCourse.getCourseId());
        List<UserCourse> userCourses = userCourseMapper.selectList(userCourseQueryWrapper);
        if(userCourses.size()==0) {
            int insert = userCourseMapper.insert(userCourse);
            if(insert ==1) {
                return Result.success("添加成功", true);
            }
            return Result.success("添加失败", false);
        }
        return Result.success("已经添加过了！", false);
    }
    @GetMapping("/findAll")
    private Result insert(Integer id) {
        QueryWrapper<UserCourse> userCourseQueryWrapper = new QueryWrapper<>();
        userCourseQueryWrapper.eq("user_id", id);
        List<UserCourse> userCourses = userCourseMapper.selectList(userCourseQueryWrapper);
        userCourses.forEach(item -> {
            Integer courseId = item.getCourseId();
            Course course = courseMapper.selectById(courseId);
            item.setCourse(course);
        });
        return Result.success("获取成功", userCourses);
    }
}
